package com.seecen.HJM.controller;

import com.seecen.HJM.result.DataVo;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.MinioException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/user/upload")
public class UploadController {

    @Value("${minio.endpoint}")
    private String minioEndpoint;

    @Value("${minio.accessKey}")
    private String accessKey;

    @Value("${minio.secretKey}")
    private String secretKey;

    @Value("${minio.bucket}")
    private String bucketName;

    /**
     * 上传用户头像到MinIO
     */
    @PostMapping("/avatar")
    public DataVo<?> uploadAvatar(@RequestParam("file") MultipartFile file) {
        // 检查文件是否为空
        if (file.isEmpty()) {
            return DataVo.error("上传文件不能为空");
        }

        // 检查文件类型
        String contentType = file.getContentType();
        if (contentType == null || (!contentType.startsWith("image/"))) {
            return DataVo.error("只支持图片格式");
        }

        // 检查文件大小（不超过2MB）
        if (file.getSize() > 2 * 1024 * 1024) {
            return DataVo.error("文件大小不能超过2MB");
        }

        try {
            // 初始化MinIO客户端
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioEndpoint)
                    .credentials(accessKey, secretKey)
                    .build();

            // 检查存储桶是否存在，不存在则创建
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
                System.out.println("创建存储桶: " + bucketName);
            }

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String suffix = null;
            if (originalFilename != null) {
                suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            }

            // 创建日期目录结构
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            String datePath = sdf.format(new Date());
            String fileName = "avatar/" + datePath + "/" + UUID.randomUUID() + suffix;

            System.out.println("上传文件到MinIO: " + fileName);

            // 上传文件到MinIO
            try (InputStream inputStream = file.getInputStream()) {
                minioClient.putObject(
                        PutObjectArgs.builder()
                                .bucket(bucketName)
                                .object(fileName)
                                .stream(inputStream, file.getSize(), -1)
                                .contentType(file.getContentType())
                                .build()
                );
            }

            // 构建文件访问URL
            String fileUrl = minioEndpoint + "/" + bucketName + "/" + fileName;
            System.out.println("文件访问URL: " + fileUrl);

            return DataVo.success(fileUrl, "头像上传成功");
        } catch (MinioException e) {
            System.err.println("MinIO错误: " + e.getMessage());
            e.printStackTrace();
            return DataVo.error("MinIO上传失败: " + e.getMessage());
        } catch (InvalidKeyException | NoSuchAlgorithmException e) {
            System.err.println("认证错误: " + e.getMessage());
            e.printStackTrace();
            return DataVo.error("认证失败: " + e.getMessage());
        } catch (IOException e) {
            System.err.println("IO错误: " + e.getMessage());
            e.printStackTrace();
            return DataVo.error("文件读取失败: " + e.getMessage());
        } catch (Exception e) {
            System.err.println("系统错误: " + e.getMessage());
            e.printStackTrace();
            return DataVo.error("系统错误: " + e.getMessage());
        }
    }
}